package com.juc.learn.CustomCommunications;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName:ShareResource
 * Package:com.juc.learn.CustomCommunications
 * Description:
 *
 * @Author:@郭先森
 * @Create:2025/7/26 - 17:46
 * @Version:v1.0
 */
public class ShareResource {
    private int flag=1;//1代表AA线程
                       //2代表BB线程
                       //3代表CC线程
    private Lock lock = new ReentrantLock();
    //创建3个Condition
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    //线程A执行
    public void printThreadA(int loop) throws InterruptedException {
        lock.lock();
        try {
            while (flag!=1){
                condition1.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+"第"+i+"次打印");
            }
            flag=2;
            condition2.signal();//通知BB线程
        }finally {
            lock.unlock();
        }
    }

    //线程B执行
    public void printThreadB(int loop) throws InterruptedException {
        lock.lock();
        try {
            while (flag!=2){
                condition2.await();
            }
            for (int i = 0; i < 6; i++) {
                System.out.println(Thread.currentThread().getName()+"第"+i+"次打印");
            }
            flag=3;
            condition3.signal();//通知CC线程
        }finally {
            lock.unlock();
        }
    }

    //线程B执行
    public void printThreadC(int loop) throws InterruptedException {
        lock.lock();
        try {
            while (flag!=3){
                condition3.await();
            }
            for (int i = 0; i < 6; i++) {
                System.out.println(Thread.currentThread().getName()+"第"+i+"次打印");
            }
            flag=1;
            condition1.signal();//通知AA线程
        }finally {
            lock.unlock();
        }
    }







}
